package com.mathlearning.auth.service;

import com.mathlearning.auth.repository.ProblemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class DailyProblemPoolService {
    
    @Autowired
    private ProblemRepository problemRepository;
    
    // 题目池缓存 - 存储可用的题目ID
    private final Set<Long> problemPool = ConcurrentHashMap.newKeySet();
    
    // 题目池锁，确保线程安全
    private final Object poolLock = new Object();
    
    // 池子大小限制，避免内存过大
    private static final int MAX_POOL_SIZE = 1000;
    
    @PostConstruct
    public void initProblemPool() {
        refreshProblemPool();
    }
    
    /**
     * 刷新题目池
     */
    public void refreshProblemPool() {
        synchronized (poolLock) {
            try {
                // 清空现有池子
                problemPool.clear();
                
                // 从数据库获取所有可用题目ID
                List<Long> availableIds = problemRepository.findAll()
                        .stream()
                        .filter(problem -> problem.getDeleted() == 0) // 未删除
                        .map(problem -> problem.getId())
                        .limit(MAX_POOL_SIZE) // 限制池子大小
                        .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
                
                // 添加到池子中
                problemPool.addAll(availableIds);
                
                System.out.println("题目池已刷新，当前池子大小: " + problemPool.size());
                
            } catch (Exception e) {
                System.err.println("刷新题目池失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 从题目池中随机获取一道题目ID，排除指定ID
     */
    public Long getRandomProblemIdFromPoolExcluding(Set<Long> excludedProblemIds) {
        synchronized (poolLock) {
            try {
                // 如果池子为空，尝试刷新
                if (problemPool.isEmpty()) {
                    refreshProblemPool();
                    if (problemPool.isEmpty()) {
                        return null;
                    }
                }
                
                // 创建可用题目列表（排除已看过的）
                List<Long> availableIds = problemPool.stream()
                        .filter(id -> !excludedProblemIds.contains(id))
                        .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
                
                if (availableIds.isEmpty()) {
                    // 如果所有题目都被排除了，清空排除列表重新选择
                    availableIds = new ArrayList<>(problemPool);
                }
                
                if (availableIds.isEmpty()) {
                    return null;
                }
                
                // 使用ThreadLocalRandom确保更好的随机性
                int randomIndex = ThreadLocalRandom.current().nextInt(availableIds.size());
                Long selectedId = availableIds.get(randomIndex);
                
                // 从池子中移除已选择的题目，避免短时间内重复
                problemPool.remove(selectedId);
                
                // 如果池子太小，补充新题目
                if (problemPool.size() < 10) {
                    refreshProblemPool();
                }
                
                return selectedId;
                
            } catch (Exception e) {
                System.err.println("从题目池获取题目失败: " + e.getMessage());
                return null;
            }
        }
    }
    
    /**
     * 获取当前池子大小
     */
    public int getPoolSize() {
        return problemPool.size();
    }
    
    /**
     * 手动刷新池子（供管理接口调用）
     */
    public void forceRefreshPool() {
        refreshProblemPool();
    }
}



